package com.github.chirspan.xaas.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.chirspan.xaas.log.annotation.ApiLog;
import com.github.chirspan.xaas.core.exception.BizException;
import com.github.chirspan.xaas.core.util.HeaderSecurityUtils;
import com.github.chirspan.xaas.mybatis.model.BaseModel;
import com.github.chirspan.xaas.mybatis.service.IBaseService;
import com.github.chirspan.xaas.core.rest.RestResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author chenpan
 * @ClassName: BaseCRUDRestController
 * description: 基础CRUD 控制器
 * @date 2018-04-03 17:30
 */

public abstract class BaseCRUDRestController<T extends BaseModel> {

    @Autowired
    protected IBaseService<T> baseService;

    @GetMapping("/_one")
    @ApiOperation(value = "根据主键查询数据", authorizations = {@Authorization(value = "apiKey")})
    public RestResult getById(@RequestParam String id) {
        return RestResult.OK(baseService.selectById(id));
    }

    @GetMapping()
    @ApiOperation(value = "分页查询", authorizations = {@Authorization(value = "apiKey")})
    public RestResult pageList(@ApiParam("查询条件实体") T m,
                               @ApiParam("页码") @RequestParam(name = "pageNo", required = false, defaultValue = "1")
                                       Integer pageNo,
                               @ApiParam("每页数量") @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                                       Integer pageSize) throws IllegalAccessException {

        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 10 : pageSize;

        Page<T> page = new Page<>(pageNo, pageSize);
        // IPage pageInfo = baseService.pageList(page, BaseCRUDWrapper.query(m));
        IPage pageInfo = baseService.pageList(page, BaseCRUDWrapper.baseQueryWrapper(m));
        return RestResult.OK(pageInfo);
    }

    @GetMapping("/_all")
    @ApiOperation(value = "查询", authorizations = {@Authorization(value = "apiKey")})
    public RestResult List(@ApiParam("查询条件实体") T m) throws IllegalAccessException {

        List<T> rs = baseService.selectByWrapper(BaseCRUDWrapper.query(m));
        return RestResult.OK(rs);
    }

    @PostMapping()
    @ApiOperation(value = "新增", authorizations = {@Authorization(value = "apiKey")})
    @ApiLog(value = "新增")
    public RestResult add(@ApiParam("新增实体") @RequestBody @Validated T m, BindingResult result) throws RemoteException, BindException {
        try {
            m.setCreateBy(HeaderSecurityUtils.getUserName());
            baseService.add(m);

            return RestResult.OK(m.getId(), "新增成功");
        } catch (Exception e) {
            throw new BizException("新增失败:" + e.getMessage());
        }
    }

    @PutMapping("/{id:.+}")
    @ApiOperation(value = "根据ID更新", authorizations = {@Authorization(value = "apiKey")})
    @ApiLog(value = "根据ID更新")
    public RestResult update(@PathVariable("id") String id, @RequestBody @Validated T m, BindingResult result) throws RemoteException {
        m.setUpdateBy(HeaderSecurityUtils.getUserName());
        m.setUpdateTime(new Date());
        m.setUpdateCount(m.getUpdateCount() == null ? 0 : m.getUpdateCount() + 1);
        baseService.updateNotNull(m);

        return RestResult.OK(id, "更新成功");
    }

    @DeleteMapping("/{id:.+}")
    @ApiOperation(value = "根据ID删除", authorizations = {@Authorization(value = "apiKey")})
    @ApiLog(value = "根据ID删除")
    public RestResult delete(@PathVariable("id") String id) {
        baseService.delete(id);
        return RestResult.OK(id, "删除成功");
    }


    @DeleteMapping("/_batch")
    @ApiOperation(value = "根据ID字符串批量删除", authorizations = {@Authorization(value = "apiKey")})
    @ApiLog(value = "根据ID字符串批量删除")
    public RestResult deleteBatch(String ids) {
        baseService.batchDelete(Arrays.asList(ids.split(",")));

        return RestResult.OK(ids, "批量删除成功");
    }
}
